package crp.core.security.domain.services;

import com.qwlabs.lang.C2;
import crp.core.security.domain.messages.SecurityMessages;
import crp.core.security.domain.models.RoleEntity;
import crp.core.security.domain.repositories.RoleRepository;
import crp.core.security.domain.repositories.UserRoleRepository;
import crp.core.shared.cache.CacheNames;
import io.quarkus.cache.CacheInvalidateAll;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.Set;

@ApplicationScoped
public class RoleEditor {
    private final RoleRepository roleRepository;
    private final UserRoleRepository userRoleRepository;

    @Inject
    public RoleEditor(RoleRepository roleRepository,
                      UserRoleRepository userRoleRepository) {
        this.roleRepository = roleRepository;
        this.userRoleRepository = userRoleRepository;
    }

    @CacheInvalidateAll(cacheName = CacheNames.ROLES_ALL)
    public RoleEntity update(String id, String name, Set<String> permissions) {
        RoleEntity role = roleRepository.findByIdOptional(id)
                .orElseThrow(() -> SecurityMessages.INSTANCE.roleNotFound(id));
        role.setName(name);
        role.setPermissions(C2.list(permissions));
        roleRepository.persist(role);
        return role;
    }

    @CacheInvalidateAll(cacheName = CacheNames.ROLES_ALL)
    public boolean delete(String id) {
        userRoleRepository.deleteByRoleId(id);
        return roleRepository.deleteById(id);
    }

    @CacheInvalidateAll(cacheName = CacheNames.ROLES_ALL)
    public RoleEntity create(String name, Set<String> permissions) {
        RoleEntity role = new RoleEntity();
        role.setName(name);
        role.setPermissions(C2.list(permissions));
        roleRepository.persist(role);
        return role;
    }
}
